package com.common.android.volley.toolbox;

import android.content.Context;
import android.text.TextUtils;

import com.common.android.volley.AuthFailureError;
import com.common.android.volley.Request;
import com.common.android.volley.RequestQueue;
import com.common.android.volley.Response;
import com.common.android.volley.VolleyError;
import com.common.dongqiuhui.apps.comm.tools.BallLog;
import com.common.dongqiuhui.apps.comm.tools.BallUtil;
import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;

import org.json.JSONObject;

import java.net.URI;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Map;

/**
 * Created by sam on 15/8/7.
 */
public class VolleyManager {
    private static VolleyManager instance=null;
    private static RequestQueue mRequestQueue;
    private boolean isUrlEncodingEnabled = true;
    private static Context mContext;
    private static final String TAG = VolleyManager.class.getSimpleName();
    public static void init(Context context) {
        mContext=context;
        mRequestQueue=Volley.newRequestQueue(context);
    }
    public static VolleyManager getInstance() {
        if (instance == null) {
            synchronized (VolleyManager.class) {
                if (instance == null) {
                    instance = new VolleyManager();
                }
            }
        }
        return instance;
    }

    public void postString(String url, final Map map,RequestListener requestListener,Class classOfT){
        StringRequest stringRequest=new StringRequest(Request.Method.POST,url,responseListener1(requestListener,classOfT),errorListener(requestListener)){

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return map;
            }
        };
        RequestParams newParams = null;
        if(map!=null) {
            newParams = convertParams(map);
        }
        String getUrl = getUrlWithQueryString(isUrlEncodingEnabled, url, newParams);
        BallLog.i(TAG, getUrl);
        executeRequest(stringRequest);
    }
    public void post(String url,Map map,RequestListener requestListener,Class classOfT){
        JsonObjectPostRequest jsonObjectPostRequest=new JsonObjectPostRequest(url,
                responseListener(requestListener,classOfT),errorListener(requestListener) ,map);
        RequestParams newParams = null;
        if(map!=null) {
             newParams = convertParams(map);
        }
            String getUrl = getUrlWithQueryString(isUrlEncodingEnabled, url, newParams);
        BallLog.i(TAG, getUrl);

        executeRequest(jsonObjectPostRequest);

    }
    public void get(String url,Map map,RequestListener requestListener,Class classOfT){
        if(map!=null) {
            RequestParams newParams = convertParams(map);
            url = getUrlWithQueryString(isUrlEncodingEnabled, url, newParams);
            BallLog.i(TAG, url);
        }
        JsonObjectRequest jsonbjectRequest=new JsonObjectRequest(url,null,responseListener(requestListener,classOfT),errorListener(requestListener));
        executeRequest(jsonbjectRequest);
    }
    protected void executeRequest(Request<?> request) {
        addRequest(request, this);
    }
    public static void addRequest(Request<?> request, Object tag) {
        if (tag != null) {
            request.setTag(tag);
        }
        if(mRequestQueue==null){
            mRequestQueue=Volley.newRequestQueue(mContext);
        }
        mRequestQueue.add(request);
    }
    /**
     * 成功消息监听 返回对象
     *
     * @param
     * @return
     */

    protected static Response.Listener<String> responseListener1(final RequestListener listener, final Class classOfT){
        return new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                BallLog.i("hgl","response="+response);
                Gson gson=new Gson();
                try {

                    listener.requestSuccess(gson.fromJson(response, classOfT));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        };

    }
    protected static Response.Listener<JSONObject> responseListener(
            final RequestListener listener, final Class classOfT) {
            return new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    JSONObject jsonObject= (JSONObject) response;
                    Gson gson=new Gson();
                    try {
                        listener.requestSuccess(gson.fromJson(response.toString(), classOfT));
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            };
    }
    protected  static Response.ErrorListener errorListener(final RequestListener requestListener){
        return new Response.ErrorListener(){
            @Override
            public void onErrorResponse(VolleyError error) {
                BallLog.i("fyh","23141onErrorResponse");
                if (!BallUtil.hasNetwork(mContext)) {
                     error.setNonetResponse(true);
                }
                requestListener.requestError(error);
            }
        };

    }
//    protected static Response.ErrorListener errorListener=new Response.ErrorListener() {
//        @Override
//        public void onErrorResponse(VolleyError error) {
//
//            Log.i("fyh","error="+error.getMessage());
//        }
//    };
    private static RequestParams convertParams(Map<String,String> params) {
        RequestParams result = new RequestParams();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }
    public static String getUrlWithQueryString(boolean shouldEncodeUrl, String url, RequestParams params) {
        if (url == null)
            return null;

        if (shouldEncodeUrl) {
            try {
                String decodedURL = URLDecoder.decode(url, "UTF-8");
                URL _url = new URL(decodedURL);
                URI _uri = new URI(_url.getProtocol(), _url.getUserInfo(), _url.getHost(), _url.getPort(), _url.getPath(), _url.getQuery(), _url.getRef());
                url = _uri.toASCIIString();
            } catch (Exception ex) {
                // Should not really happen, added just for sake of validity
            }
        }

        if (params != null) {
            // Construct the query string and trim it, in case it
            // includes any excessive white spaces.
            String paramString = params.toString().trim();

            // Only add the query string if it isn't empty and it
            // isn't equal to '?'.
            if (!paramString.equals("") && !paramString.equals("?")) {
                url += url.contains("?") ? "&" : "?";
                url += paramString;
            }
        }

        return url;
    }
    public static  String removeBOM(String data) {
        if (TextUtils.isEmpty(data)) {
            return data;
        }

        if (data.startsWith("\ufeff")) {
            return data.substring(1);
        } else {
            return data;
        }
    }
}
